// pages/enterprise/enterprise.js
const createRecycleContext = require('miniprogram-recycle-view')
import {
    addBindCompanySupplier,
    getBindCompanySupplier,
    updateCompanySupplier,
    getEnterpriseList,
    getEnsureDetailApi,
    updateForbiddenApi
} from '../../api/app.js'
import {
    anit,
    shake
} from '../../utils/util.js'
import user from '../../utils/user.js'
const app = getApp()
let ctx = null
Page({

    /**
     * 页面的初始数据
     */
    data: {
        currentisdis: false,
        periodServeCompanyId: '',
        jyid: '',
        selectdata: {},
        addId: '',
        iszk: true,
        showpopjy1: false,
        showpopjy2: false,
        // 是否管理员
        isAdmin: false,
        isSuperAdmin: false,
        isSelect: false,
        selects: [],

        // 更多操作提示设置
        moreList: [],
        moreTop: 0,
        moreStatus: false,

        // 数据
        enterprise: {
            name: '',
            director: '',
            phone: '',
            creditCode: '',
            ofSystem: false,
            isNeedIdcardPhoto: true
        },

        // 弹窗控制
        popupTitle: '',
        popupShow: false,
        popupForm: [],
        popupSuccess: '',

        // 两个数据列表
        enterpriseList: [],
        supplierList: [],
        tipList: [],

        // 内容搜索
        searchText: '',

        tyrb: '',
        showDialog: false,
        insureData: {},
        windowHeight: 0
    },
    async getEnsureDetailFn(id) {
        let res = await getEnsureDetailApi({
            id: id
        })
        this.setData({
            applicationForInsuranceListLong: res.occupationList ?? [],
            applicationForInsuranceListDay: res.industryName ?? '',
            applicationForInsuranceListTeam: res.industryNameTYX ?? '',
            isOpenInsurinfo: res.isOpenInsur,
            isOpenWesureinfo: res.isOpenWesure,
            periodServeCompanyId: res.periodServeCompanyId,
            insureData: res
        })
        console.log(res, 'dgfyhuy')
    },
    onToaddPage() {
        if (user.isOpenPeriodInsur) {
            if (this.data.insureData.periodServeCompanyBlacklistStatus === 1 || this.data.insureData.periodServeCompanyStatus === 3) {
                wx.showToast({
                    title: '禁用状态不可申请',
                    icon: 'none'
                })
            } else {
                if (!this.data.isOpenInsurinfo) {
                    wx.navigateTo({
                        url: '/packageLongInsure/pages/dispatch-add/dispatch-add?id=' + this.data.selects[0].id + '&name=' + this.data.selects[0].name + '&area=' + this.data.selects[0].area + '&addType=isfirstapply' + '&dis=1',
                    })
                } else {
                    console.log(2)
                    wx.navigateTo({
                        url: '/packageLongInsure/pages/dispatch-add/dispatch-add?id=' + this.data.periodServeCompanyId + '&addType=apply',
                    })
                }
            }
        } else {
            wx.navigateTo({
                url: '/pages/product-presentation/product-presentation?type=2',
            })
        }
    },
    changezkgb() {
        if (this.data.iszk) {
            this.setData({
                iszk: false
            })
        } else {
            this.setData({
                iszk: true
            })
        }
    },
    onReady() {},
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(2)
        console.log(options.searchOpenWesure, 'options.searchOpenWesure')
        console.log(33333, wx.getSystemInfoSync())
        this.setData({
            isAdmin: user.isAdmin,
            isSuperAdmin: user.isSuperAdmin,
            isSelect: !!options.select,
            isRadio: options.radio,
            searchOpenWesure: Number(options.searchOpenWesure),
            tyrb: options.tyrb,
            windowHeight: wx.getSystemInfoSync().windowHeight
        }, () => {
            console.log(this.data.searchOpenWesure, 'searchOpenWesure')
        })
        // const eventChannel = this.getOpenerEventChannel()
        // eventChannel.on('selects', (data) => {
        //     const selects = data.map(id=>{
        //         return {id}
        //     })
        //     this.setData({
        //         selects
        //     },()=>{
        //         console.log(selects)
        //     })
        // })
    },
    initCtx() {
        ctx = createRecycleContext({
            id: 'recycleId',
            dataKey: 'recycleList',
            page: this,
            itemSize: { // 这个参数也可以直接传下面定义的 this.itemSizeFunc 函数
                width: (wx?.getWindowInfo && wx.getWindowInfo()?.screenWidth || 750) / 750 * 690,
                height: (wx?.getWindowInfo && wx.getWindowInfo()?.screenWidth || 750) / 750 * 400
            }
        })
        ctx.splice(0, ctx.comp.sizeArray.length)
    },
    onShow() {
        user.waitLogin().then(() => {
            this.initCtx()
            this.showEnterprise(null, this.data.searchOpenWesure)
        })
    },
    addsuccess(res) {
        this.data.selects.push({
            id: res,
        })
        console.log(this.data.selects, 'selects')
        this.showEnterprise(null, this.data.searchOpenWesure)
    },
    // 更新并显示企业信息
    showEnterprise(searchText = null, searchOpenWesure = null) {
        console.log(1233, ctx, this.data.enterpriseList.length)
        ctx.splice(0, this.data.enterpriseList.length)
        getBindCompanySupplier({
            companyId: user.companyId,
            serveCompanyName: searchText,
            searchOpenWesure: searchOpenWesure,
            insureCompanyType: this.data.tyrb ? 'insure_type_tyrb' : null
        }).then(res => {
            if (!res.length) {
                app.toast('暂无绑定信息')
            }
            ctx.append(res)
            this.setData({
                'enterpriseList': res
            })
        })
    },
    // 添加企业
    onAddEnterprise() {
        wx.navigateTo({
            url: '/pages/enterprise-add/enterprise-add',
            events: {
                acceptDataFromOpenedPage: function (data) {
                    console.log(data)
                },
                someEvent: function (data) {
                    console.log(data)
                }
            }
        })
        // this.showPopupForm('添加企业')
    },
    // 提交企业
    onSubmitEnterprise() {
        const data = this.data.enterprise
        console.log(data, 'datadata')
        if (data.phone.length > 0 && !/^1\d{10}$/.test(data.phone)) {
            app.toast('请输入正确的手机号码')
            return 0
        }
        // 企业名称不来源于后台提供
        if (!data.ofSystem) {
            app.toast('请在下拉列表中选择对应的企业名称')
            return 0
        }
        this.setData({
            enterprise: {}
        })
        addBindCompanySupplier({
            companyId: user.companyId,
            serveCompanyName: data.name,
            creditCode: data.creditCode,
            contacts: data.director,
            area: data.base || '暂无',
            phone: data.phone,
            createUserId: user.userId,
            isNeedIdcardPhoto: Number(data.isNeedIdcardPhoto),
            contactsId: data.id
        }).then(res => {
            console.log(res, '添加啦')
            app.toast('添加成功', 'success')
            // this.data.enterpriseList.unshift({
            //     auditStatus: 1,
            //     contacts: data.director,
            //     createTime: this.dateFormat('YYYY-mm-dd HH:MM:SS',new Date()),
            //     createUserId: user.userId,
            //     creditCode: data.creditCode,
            //     id: res,
            //     isNeedIdcardPhoto: Number(data.isNeedIdcardPhoto),
            //     isNotDefault: 0,
            //     phone: data.phone,
            //     serveCompanyName: data.name
            // })
            // this.setData({
            //     'enterpriseList': this.data.enterpriseList
            // })
            this.data.selects.push({
                id: res,
            })
            // this.setData({
            //     selects: this.data.selects
            // })
            console.log(this.data.selects, 'selects')
            this.showEnterprise(null, this.data.searchOpenWesure)
        })
        this.hidePopupForm()
    },
    // 企业名称修改，提示
    onEnterpriseName(event) {
        if (event.detail.value) {
            shake(() => {
                this.setData({
                    ['enterprise.ofSystem']: false,
                    ['enterprise.creditCode']: ''
                })

                getEnterpriseList({
                    name: event.detail.value
                }).then(res => {
                    this.setData({
                        tipList: res
                    })
                })
            })
        }
    },
    // 点击提示
    onTapEnter(event) {
        this.setData({
            ['enterprise.ofSystem']: true,
            ['enterprise.name']: event.currentTarget.dataset.name,
            ['enterprise.creditCode']: event.currentTarget.dataset.code,
            ['enterprise.base']: event.currentTarget.dataset.base,
            tipList: []
        })
    },
    search(event) {
        shake(() => {
            this.showEnterprise(event.detail.value, this.data.searchOpenWesure)
        })
    },
    onNoticeGo() {
        wx.navigateTo({
            url: '/pages/flow/set/set?id='
        })
    },
    // 选择企业
    onSelect(event) {
        let selects = this.data.selects
        const data = event.currentTarget.dataset
        console.log(data, selects, 'data')
        if (this.data.isRadio) { // 单选
            selects = [{
                name: data.name,
                id: data.id,
                position: data.position,
                phone: data.phone,
                area: data.area
            }]
        } else { // 多选
            let index = -1
            for (const i in selects) {
                if (selects[i].id === data.id) {
                    index = i
                }
            }
            if (index === -1) {
                selects.push({
                    id: data.id,
                })
            } else {
                selects.splice(index, 1)
            }
        }

        this.setData({
            selects
        })
    },
    // 选择完成后返回选中内容
    onSelectComplete() {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('complete', this.data.selects)
        wx.navigateBack()
    },
    // // 更多显示控制
    // more(event) {
    // 	this.setData({
    // 		'moreList': [{
    // 				text: '编辑',
    // 				key: event.currentTarget.dataset.type + '-' + event.currentTarget.dataset.index,
    // 				icon: '/packagePay/assets/img/enterprise/edit.png',
    // 				bind: 'edit'
    // 			},
    // 			{
    // 				text: '删除',
    // 				key: event.currentTarget.dataset.type + '-' + event.currentTarget.dataset.index,
    // 				icon: '/packagePay/assets/img/enterprise/delete.png',
    // 				bind: 'deleteT'
    // 			}
    // 		]
    // 	})
    // 	this.setData({
    // 		'moreTop': event.touches[0].clientY + 6,
    // 		'moreStatus': true,
    // 	})
    // },
    // // 隐藏更多
    // hideMore() {
    // 	this.setData({
    // 		'moreStatus': false
    // 	})
    // },

    // 更多操作，编辑
    // edit(event) {
    // 	const data = event.detail.split('-')
    // 	const type = data[0]
    // 	const index = data[1]
    // 	console.log(type)
    //
    // 		this.showPopupForm('修改企业信息')
    //
    // 	// updateCompanySupplier({
    // 	// 	id: this.data[type][index].phone,
    // 	// 	isDelete: 1,
    // 	// 	updateUserId: user.userId
    // 	// })
    // },
    // 更多操作，删除
    // deleteT(event) {
    // 	const data = event.detail.split('-')
    // 	const type = data[0]
    // 	const index = data[1]
    // 	updateCompanySupplier({
    // 		id: this.data[type][index].id,
    // 		isDelete: 1,
    // 		updateUserId: user.userId
    // 	})
    // },

    closetbsq() {
        console.log(111)
        this.setData({
            showDialog: false
        })
    },
    // 更多操作，编辑完成提交
    editMsg(event) {
        console.log(event)
        app.confirm('是否确定修改?').then(() => {
            updateCompanySupplier({
                id: event.detail.id,
                contacts: event.detail.director,
                phone: event.detail.phone,
                updateUserId: user.userId,
                supplierName: event.detail.name
            }).then(() => {
                app.toast('操作成功')
                this.hidePopupForm()
            })
        })
    },
    inputchange(event) {
        this.setData({
            [event.currentTarget.dataset.model]: event.detail.value
        })
    },
    showPopupForm(popupTitle) {
        this.setData({
            popupShow: true,
            popupTitle,
        })
    },
    hidePopupForm() {
        this.setData({
            popupShow: false,
            isInsuranceTime: false
        })
    },
    async onJysurefn() {
        console.log('禁用企业')
        let res = await updateForbiddenApi({
            id: this.data.jyid,
            isForbidden: 1
        })
        console.log(res)
        if (res) {
            wx.showToast({
                title: '操作成功',
                icon: 'none'
            })
            setTimeout(() => {
                this.showEnterprise(null, this.data.searchOpenWesure)
                this.setData({
                    showpopjy1: false
                })
            }, 300)
        }
    },
    hidepop1() {
        this.setData({
            showpopjy1: false
        })
    },
    hidepop2() {
        this.setData({
            showpopjy2: false
        })
    },
    // 编辑企业信息
    onGoToEdit(event) {
        if (this.data.isAdmin) {
            const data = this.data.enterpriseList[event.currentTarget.dataset.index]
            wx.navigateTo({
                url: `/pages/enterprise-edit/enterprise-edit?id=${data.id}&company=${data.serveCompanyName}&contacts=${data.contacts}&phone=${data.phone}&needPhoto=${data.isNeedIdcardPhoto}&isFlow=${data.isNotDefault}&isShowContacts=${data.isShowContacts}&isOpenAdvance=${data.isOpenAdvance}&isConfigAdvance=${data.isConfigAdvance}&paymentAmountCap=${data.paymentAmountCap?data.paymentAmountCap:-1}`,
                events: {
                    getlist: () => {
                        this.showEnterprise(null, this.data.searchOpenWesure)
                    }
                },
            })
        } else {
            wx.showToast({
                title: '权限不足',
                icon: 'none'
            })
        }

    },
    onSelectDirector() {
        if (anit)
            wx.navigateTo({
                url: '/pages/team-list/team-list?select=selectDirectorComplete',
            })
    },
    selectDirectorComplete(data) {
        console.log(data)
        this.setData({
            ['enterprise.director']: data[0].name,
            ['enterprise.phone']: data[0].phone,
            ['enterprise.id']: data[0].id
        })
    },
    onChangeNeedCardPhoto(event) {
        this.setData({
            ['enterprise.isNeedIdcardPhoto']: event.detail.value
        })
    },

    async handleForbidden(e) {
        if (this.data.isAdmin) {
            if (e.currentTarget.dataset.status === 1) {
                let res = await updateForbiddenApi({
                    id: e.currentTarget.dataset.id,
                    isForbidden: 0
                })
                console.log(res)
                if (res) {
                    wx.showToast({
                        title: '操作成功',
                        icon: 'none'
                    })
                    setTimeout(() => {
                        this.showEnterprise(null, this.data.searchOpenWesure)
                    }, 300)
                }
            } else {
                this.setData({
                    showpopjy1: true,
                    jyid: e.currentTarget.dataset.id
                })
                return
            }
        } else {
            wx.showToast({
                title: '权限不足',
                icon: 'none'
            })
        }


    },
    toApplicantLong() {
        if (user.isOpenWesure) {
            if (this.data.isOpenWesureinfo) {
                return
            }
            // 拉黑了
            if (this.data.insureData.wesureServeCompanyBlacklistStatus === 1) {
                wx.showToast({
                    title: '禁用状态不可申请',
                    icon: 'none'
                })
            } else {
                console.log(this.data.selectdata)
                wx.navigateTo({
                    url: '/packageInsurance/pages/insurance-organize/insurance-organize?form=list&name=' + this.data.selectdata.name + '&area=' + this.data.selectdata.area + '&id=' + this.data.selectdata.id,
                })
            }
        } else {
            wx.navigateTo({
                url: '/pages/product-presentation/product-presentation?type=3',
            })
        }


    },
    toApplicantDay() {
        if (user.isOpenWesure) {
            if (this.data.isOpenWesureinfo) {
                return
            }
            // 拉黑了
            if (this.data.insureData.wesureServeCompanyBlacklistStatus === 1) {
                wx.showToast({
                    title: '禁用状态不可申请',
                    icon: 'none'
                })
            } else {
                console.log(this.data.selectdata)
                wx.navigateTo({
                    url: '/packageMicroInsurance/pages/insurance-organize/insurance-organize?form=list&name=' + this.data.selectdata.name + '&area=' + this.data.selectdata.area + '&id=' + this.data.selectdata.id,
                })
            }
        } else {
            wx.navigateTo({
                url: '/pages/product-presentation/product-presentation?type=4',
            })
        }

    },
    handleShowDialog(e) {
        console.log(e, 'sguis')
        this.data.selectdata = {}
        console.log(e.currentTarget.dataset.info)
        let obj = {
            id: e.currentTarget.dataset.info.id,
            area: e.currentTarget.dataset.info.area,
            name: e.currentTarget.dataset.info.serveCompanyName
        }
        const selects = [{
            name: obj.name,
            id: obj.id,
            position: obj.position,
            phone: obj.phone,
            area: obj.area
        }]
        this.setData({
            selects: selects,
            showDialog: true,
            currentisdis: e.currentTarget.dataset.status,
            addId: e.currentTarget.dataset.cid,
            selectdata: obj
        })
        this.getEnsureDetailFn(e.currentTarget.dataset.id)
    }

})